package org.koin.koincomponent.customkoincomponent;

import org.koin.Simple;
import org.koin.core.Koin;
import org.koin.core.KoinApplication;
import org.koin.core.component.KoinComponent;
import org.koin.core.definition.Definition;
import org.koin.core.error.DefinitionOverrideException;
import org.koin.core.error.NoScopeDefFoundException;
import org.koin.core.error.ScopeAlreadyCreatedException;
import org.koin.core.parameter.DefinitionParameters;
import org.koin.core.scope.Scope;
import org.koin.dsl.KoinAppDeclaration;
import org.koin.dsl.Module;
import org.koin.dsl.ModuleDeclaration;

import static org.koin.dsl.KoinApplication.koinApplication;

public abstract class CustomKoinComponent implements KoinComponent {

    private static Koin customKoin;

    public static Koin customKoin() {
        if (customKoin == null) {
            try {
                customKoin = koinApplication(new KoinAppDeclaration() {
                    @Override
                    public void invoke(KoinApplication koinApplication) {
                        org.koin.core.module.Module module = Module.module(new ModuleDeclaration() {
                            @Override
                            public void invoke(org.koin.core.module.Module module) {
                                try {
                                    module.single(Simple.ComponentA.class, new Definition<Simple.ComponentA>() {
                                        @Override
                                        public Simple.ComponentA invoke(Scope scope, DefinitionParameters parameters) {
                                            return new Simple.ComponentA();
                                        }
                                    });
                                } catch (DefinitionOverrideException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                        try {
                            koinApplication.modules(module);
                        } catch (DefinitionOverrideException e) {
                            e.printStackTrace();
                        }
                    }
                }).getKoin();
            } catch (ScopeAlreadyCreatedException e) {
                e.printStackTrace();
            } catch (NoScopeDefFoundException e) {
                e.printStackTrace();
            }
        }
        return customKoin;
    }

    @Override
    public Koin getKoin() {
        return customKoin();
    }
}
